package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 根据楼层id获取房间中的智能设备及数据
     *
     * @param floorId 楼层id
     * @return 结果
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        //查询房间(床位)
        List<RoomVo> vos = roomMapper.getRoomsWithDeviceByFloorId(floorId);
        //轮询房间
        vos.forEach(room -> {
            room.getDeviceVos().forEach(rd->{
               String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, rd.getIotId());
                if (jsonStr != null && jsonStr.startsWith("\"") && jsonStr.endsWith("\"")) {
                    // 移除外层引号并处理转义字符
                    jsonStr = jsonStr.substring(1, jsonStr.length() - 1);
                    jsonStr = jsonStr.replace("\\\"", "\"")
                            .replace("\\\\", "\\");
                }
                if (ObjectUtil.isNotEmpty(jsonStr)){
                    rd.setDeviceDataVos(JSONUtil.toList(jsonStr, DeviceData.class));
                }
            });
            //轮询房间的床位
            room.getBedVoList().forEach(b -> {
                b.getDeviceVos().forEach(dv -> {
                    String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, dv.getIotId());
                    if (jsonStr != null && jsonStr.startsWith("\"") && jsonStr.endsWith("\"")) {
                        // 移除外层引号并处理转义字符
                        jsonStr = jsonStr.substring(1, jsonStr.length() - 1);
                        jsonStr = jsonStr.replace("\\\"", "\"")
                                .replace("\\\\", "\\");
                    }
                    if (ObjectUtil.isNotEmpty(jsonStr)){
                        dv.setDeviceDataVos(JSONUtil.toList(jsonStr.toString(),DeviceData.class));
                    }
                });
            });
        });
        return vos;
    }

    @Override
    public RoomVo getRoomById(Long id) {
        return roomMapper.getRoomById(id);
    }
}
